/**
 * 
 */
package org.adempiere.apps.graph;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import layout.TableLayout;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.apps.AEnv;
import org.compiere.apps.AWindow;
import org.compiere.apps.Waiting;
import org.compiere.apps.form.FormFrame;
import org.compiere.model.MAttachment;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBSCCard;
import org.compiere.model.MBSCCardLine;
import org.compiere.model.MQuery;
import org.compiere.model.MRefList;
import org.compiere.swing.CScrollPane;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.ValueNamePair;

import extend.org.compiere.utils.Util;

/**
 * @author Ибраев Е.А.
 *
 */
public class BSCCardLinePanel extends JPanel implements ActionListener, MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3021928035731559459L;

	private MBSCCardLine cardLine = null;
	private JPanel[] panels = null;
	private TableLayout tableLayout = null;
	private Dimension panelDimension = null;
	private JLabel lblName = null;
	private BSCThermometer thermometer = null; 
	private JButton[][] buttonAttachment = null;
	
	protected static int[] cellHeight = {100,0};
	
	protected int num = 0;
	
	public BSCCardLinePanel(MBSCCardLine mbscCardLine, int initNum) {
		super();
		num = initNum;
		addMouseListener(this);
		setBorder(BorderFactory.createLineBorder(Color.BLACK));
		setCardLine(mbscCardLine);
		initView();
	}

	protected void initLayout() {
		tableLayout = new TableLayout(BSCTableHeaderPanel.initTableSize(cellHeight));
		setLayout(tableLayout);
	}
	

	protected void initView() {
		removeAll();
		initLayout();
		
		panelDimension = initDimesion();
		setSize(panelDimension);
		setPreferredSize(panelDimension);
		setMaximumSize(panelDimension);
		setMinimumSize(panelDimension);

		if (cardLine != null) {
			initPanels();
			if (panels != null) {
				for(int i = 0; i < panels.length; i++) {
					String pos= Integer.toString(i)+",0";
					add(panels[i],pos);
				}
			}
		}
		
	}
	
	protected void initPanels() {
		if (cardLine != null) {
			JLabel lbl = null;
			String tmpS = null;
			Dimension d = null;
			
			panels = new JPanel[BSCTableHeaderPanel.tableHeader.length];
			panels[0] = new JPanel(); // №
			lbl = new JLabel(Integer.toString(num++));
			lbl.setHorizontalAlignment(JLabel.CENTER);
			panels[0].add(lbl);
			
			panels[1] = new JPanel(); // КПД
			tmpS = "<html><u>"+(cardLine.getName() == null ? "" : cardLine.getName())+"</u></html>";
			lblName = new JLabel(tmpS,JLabel.LEFT);
			lblName.setVerticalAlignment(JLabel.TOP);
			d = new Dimension(BSCTableHeaderPanel.cellWidth[1]-20, cellHeight[0]);
			lblName.setSize(d);
			lblName.setPreferredSize(d);
			lblName.setMinimumSize(d);
			lblName.setMaximumSize(d);
			lblName.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			panels[1].add(lblName);
			panels[1].setBorder(getBorder());
			
			panels[2] = new JPanel(); // Ед. Изм.
			tmpS = getRefListValue(cardLine.getUnit());
			lbl = new JLabel(tmpS);
			panels[2].add(lbl);
			panels[2].setBorder(getBorder());
			
			panels[3] = new JPanel(); // Вес %
			tmpS =  String.format("%.2f%n", cardLine.getWeight());
			lbl = new JLabel(tmpS);
			panels[3].add(lbl);
			panels[3].setBorder(getBorder());
			
			panels[4] = new JPanel(); // План
			tmpS =  String.format("%.2f%n", cardLine.getValueMin());
			lbl = new JLabel(tmpS);
			panels[4].add(lbl);
			panels[4].setBorder(getBorder());
			
			panels[5] = new JPanel(); // Факт
			lbl = new JLabel(cardLine.getValue());
			panels[5].add(lbl);
			panels[5].setBorder(getBorder());

			panels[6] = new JPanel(); // Расчет показателя
			tmpS = (cardLine.getDescription() == null ? "" : cardLine.getDescription());
			
			lbl = new JLabel("<html>" + tmpS + "</html>");
			
			d = new Dimension(BSCTableHeaderPanel.cellWidth[6]-20, cellHeight[0]-3);
			lbl.setVerticalAlignment(JLabel.TOP);
			lbl.setSize(d);
			lbl.setPreferredSize(d);
			lbl.setMinimumSize(d);
			
			CScrollPane scroll =  new CScrollPane(lbl);
			scroll.setSize(d);
			scroll.setPreferredSize(d);
			scroll.setMinimumSize(d);
			scroll.setMaximumSize(d);
			panels[6].add(lbl);
			panels[6].setBorder(getBorder());
			
			panels[7] = new JPanel(); // Примечание
			tmpS = cardLine.getMessage();
			lbl = new JLabel("<html>"+tmpS+"</html>");
			lbl.setVerticalAlignment(JLabel.TOP);
			d = new Dimension(BSCTableHeaderPanel.cellWidth[7]-3, cellHeight[0]-3);
			scroll =  new CScrollPane(lbl);
			lbl.setSize(d);
			lbl.setPreferredSize(d);
			lbl.setMinimumSize(d);
			scroll.setSize(d);
			scroll.setPreferredSize(d);
			scroll.setMinimumSize(d);
			scroll.setMaximumSize(d);
			panels[7].add(lbl);
			panels[7].setBorder(getBorder());
			
			
			panels[8] = new JPanel(); // Ссылка на прикрепление
			JPanel panel = new JPanel();
			d = new Dimension(BSCTableHeaderPanel.cellWidth[8]-3, cellHeight[0]+10);
			panel.setSize(d);
			panel.setPreferredSize(d);
			addAttachmentButtons(panel);
			d = new Dimension(BSCTableHeaderPanel.cellWidth[8]-3, cellHeight[0]-3);
			scroll = new CScrollPane(panel);
			scroll.setSize(d);
			scroll.setPreferredSize(d);
			scroll.setMinimumSize(d);
			scroll.setMaximumSize(d);
			panels[8].add(scroll);
			//TODO
			
			
			double value = cardLine.getValueNumber().doubleValue();
			Color c;
			if (value > 0) c = Color.GREEN;
			else c = Color.RED;
			
			panels[9] = new JPanel(); //Статус
			BSCPointPanel pp = new BSCPointPanel(c);
			int size = BSCTableHeaderPanel.cellHeight[0] / 3;
			d = new Dimension(size, size);
			pp.setSize(d);
			pp.setPreferredSize(d);
			pp.setMinimumSize(d);
			pp.setMaximumSize(d);
			panels[9].add(pp);
			panels[9].setBorder(getBorder());
		}
	}
	
	public void addAttachmentButtons(JPanel panel) {
		buttonAttachment = new JButton[cardLine.getAttachments().length][];
		for(int i = 0; i < cardLine.getAttachments().length; i++) {
			MAttachment attachment = cardLine.getAttachments()[i];
			int BSC_CardLine_ID = cardLine.getAttachments()[i].getRecord_ID();
			MBSCCardLine cl = new MBSCCardLine(Env.getCtx(),BSC_CardLine_ID,null);
			String bpName = cl.getCard().getC_BPartner().getName();
			buttonAttachment[i] = new JButton[attachment.getEntries().length];
			
			for(int j = 0 ; j < attachment.getEntries().length; j++) {
			  buttonAttachment[i][j] = new JButton(Integer.toString(i+1)+"."+Integer.toString(j+1)+".Вложение "+bpName);
			  panel.add(buttonAttachment[i][j]);
			  buttonAttachment[i][j].addActionListener(this);
			}
		}
	}
	
	public MBSCCardLine getCardLine() {
		return cardLine;
	}

	public void setCardLine(MBSCCardLine cardLine) {
		this.cardLine = cardLine;
	}

	/**
	 * @param unit
	 * @return
	 */
	private String getRefListValue(String unit) {
		String result = null;
		int AD_Reference_ID = DB.getSQLValue(null, "SELECT AD_Reference_ID FROM AD_Reference  WHERE Name = 'UnitCard'");
		ValueNamePair[] vnpList = MRefList.getList(Env.getCtx(), AD_Reference_ID, false);
		for(ValueNamePair vnp : vnpList) {
			if (vnp.getValue().equals(unit)) {
				result = vnp.getName();  
			}
		}
		return result;
	}
	
	private Dimension initDimesion() {
		int width = 0;
		int height = 0;
			
		for(int i=0; i < BSCTableHeaderPanel.tableSize[0].length; i++) {
			width += BSCTableHeaderPanel.tableSize[0][i];
			height += BSCTableHeaderPanel.tableSize[1][i];
		}
		panelDimension = new Dimension(width,height);
		return panelDimension;
	}

	private boolean isTitle(MouseEvent e) {
		int y = panels[0].getY();
		int x = panels[2].getX() - 10;
		int height = panels[0].getHeight();
		
		boolean result = (y < e.getY() && e.getY() < y + height && e.getX() < x);
		
		return result;
	}
	
	/**
	 * 
	 */
	private void openCardWindow(int BSC_CardLine_ID) {
		lblName.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		System.out.print("BSC_CardLine_ID = ");System.out.print(BSC_CardLine_ID);System.out.println("");
		MBSCCard card = cardLine.getCard();
		
		AWindow myWindow = new AWindow(getGraphicsConfiguration());
		int AD_Window_ID = BSCCardPanelNew.getBSC_CardWindow_ID();
		MQuery query = new MQuery(MBSCCard.Table_ID);
		query.addRestriction("BSC_Card_ID", MQuery.EQUAL, card.getBSC_Card_ID());
		if (BSC_CardLine_ID > 0) {
			query.setZoomTableName(MBSCCardLine.Table_Name);
			query.setZoomColumnName(MBSCCardLine.COLUMNNAME_BSC_CardLine_ID);
			query.setZoomValue(BSC_CardLine_ID);
		}
		if (myWindow.initWindow(AD_Window_ID, query)) {
			AEnv.addToWindowManager(myWindow);
			myWindow.pack();
			myWindow.setVisible(true);
			myWindow.toFront();
		};
		lblName.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	}
	
	/**
	 * @param e
	 * @return
	 */
	private boolean isTitleThermometer(MouseEvent e) {
		int y = panels[0].getY();
		int x = panels[5].getX() - 10;
		int height = panels[0].getHeight();
		
		boolean result = (y < e.getY() && e.getY() < y + height && x < e.getX());
		return result;
	}
	
	private void openBarChartWindow(int BSC_Card_ID, int BSC_CardLine_ID) {
		thermometer.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		if(BSC_Card_ID > 0) {
			FormFrame myWindow = new FormFrame(Env.getWindow(0).getGraphicsConfiguration());
			if (myWindow.openForm(BSCCardPanelNew.getBSCViewBarChart())) {
				BSCViewBarChart view = (BSCViewBarChart) myWindow.getFormPanel();
				view.setBSC_Card_ID(BSC_Card_ID);
				if (BSC_CardLine_ID > 0) {
					MBSCCardLine cl = new MBSCCardLine(Env.getCtx(),BSC_CardLine_ID,null);
					if (cl != null) {
						view.setBSC_Parameter_ID(cl.getBSC_Parameter_Out_ID());
					}
				}
				AEnv.addToWindowManager(myWindow);
				AEnv.showCenterScreen(myWindow);
				myWindow.setVisible(true);
				myWindow.setFocusableWindowState(true);
				myWindow.toFront();
			}			
		}
		thermometer.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));	
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (isTitle(e) && cardLine != null) {
			openCardWindow(cardLine.getBSC_CardLine_ID());
		} /*else if(isTitleThermometer(e) && cardLine != null) {
			openBarChartWindow(cardLine.getCard().getBSC_Card_ID(), cardLine.getBSC_CardLine_ID());
		}	*/
	}

	private Frame getFrame() {
		Frame result = null;
		Container container = getParent();
		
		while (container != null) {
			
			if(container instanceof FormFrame) {
				result = ((FormFrame) container).getFrames()[0];
				break;
			}
			container = container.getParent();
		}
		
		return result;
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getSource() instanceof JButton) {
			for(int i = 0; i < buttonAttachment.length; i++) {
				for(int j =0; j<buttonAttachment[i].length; j++) {
					if(arg0.getSource().equals(buttonAttachment[i][j])) {
						viewDialogAttachment(i,j);
						break;
					}
				}
			}
		}
		
	}
	
	private void viewDialogAttachment(int i, int j) {
		MAttachmentEntry entry = cardLine.getAttachments()[i].getEntry(j);
		File file = Util.getAttachmentEntryFile(entry);
		Util.launchFile(file);
	}
	
	
	public int getNum() {
		return num;
	}
}
